import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Row, Col, Card, Select, Input, Anchor, AutoComplete, message } from 'antd';
import queryString from 'query-string';
import router from 'umi/router';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import Authorized from '@/utils/Authorized';
import styles from '@/utils/utils.less';
import CustomerBasicInfor from './CustomerBasicInfor';
import BusinessContract from './BusinessContract';
import Quotation from './Quotation';
import OnceCharge from './OnceCharge';
import CustomerBill from './CustomerBill';
import BasicInfor from './BasicInfor';
import AddEmploeTask from './AddEmploeTask';
import ReduceEmploeTask from './ReduceEmploeTask';
import AdjustTask from './AdjustTask';
import PaymentInfor from './PaymentInfor';
import SocialHandleInfor from './SocialHandleInfor';
import RefundInfor from './RefundInfor';
import Payroll from './Payroll';
import LaborContractInfor from './LaborContractInfor';

const { Search } = Input;
const { Option } = Select;
const FormItem = Form.Item;
const { Link } = Anchor;
@connect(({ integratedquery, menu, loading }) => ({
  menu,
  loading: loading.models.integratedquery,
  empBaseInfo: integratedquery.empBaseInfo, // 员工基本信息
  addTaskList: integratedquery.addTaskList, // 增员任务列表数据
  reduceTaskList: integratedquery.reduceTaskList, // 减员任务列表数据
  adjustTaskList: integratedquery.adjustTaskList, // 调整任务列表数据
  empInsPayList: integratedquery.empInsPayList, // 社保实缴列表数据
  empAccuPayList: integratedquery.empAccuPayList, // 公积金实缴列表数据
  empInsSerInfoList: integratedquery.empInsSerInfoList, // 社保服务办理列表数据
  empInsRefundInfoList: integratedquery.empInsRefundInfoList, // 返款信息列表数据
  wageDataList: integratedquery.wageDataList, // 代发工资列表数据
  empLaborContInfoList: integratedquery.empLaborContInfoList, // 劳动合同信息数据
  custBaseInfo: integratedquery.custBaseInfo, // 客户基本信息
  custConstList: integratedquery.custConstList, // 商务合同列表数据
  crmquoDataList: integratedquery.crmquoDataList, // 报价单列表数据
  onceChargeDataList: integratedquery.onceChargeDataList, // 一次性收费列表数据
  billList: integratedquery.billList, // 客户账单列表数据
  type: integratedquery.type, // 区分客户，雇员
  custLabelObj: integratedquery.custLabelObj,
  empLabelObj: integratedquery.empLabelObj,
  custShowName: integratedquery.custShowName, // 客户显示的默认值
  empShowName: integratedquery.empShowName, // 雇员显示的默认值
}))
@Form.create()
class SearchList extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      empList: [], // 搜索雇员列表数据
      custList: [], // 搜索客户列表数据
      custId: null, // 客户id
      name: null, // 客户名称
      empName: null, // 员工姓名
      certNo: null, // 证件号
    };
  }

  componentDidMount() {
    const { location, custLabelObj, empLabelObj, type } = this.props;
    const { isMenuLink } = queryString.parse(location.search);
    if (isMenuLink === 'true') {
      this.resetAndGeLlist(location);
    } else if (type === 1) {
      // 客户
      if (custLabelObj) {
        this.setState({ custId: custLabelObj.key, name: custLabelObj.label });
      }
    } else if (empLabelObj) {
      // 雇员
      const empKeyObj = empLabelObj.key;
      const empKeyArr = empKeyObj.split(' ');
      const empLabelObjs = empLabelObj.label;
      const empLabelArr = empLabelObjs.split(' ');
      this.setState({ empName: empLabelArr[0], certNo: empKeyArr[1] });
    }
  }

  // 清除所有的历史记录数据
  delAllListData = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'integratedquery/updateModalData',
      payload: {
        type: 1,
        custLabelObj: undefined,
        empLabelObj: undefined,
        empBaseInfo: {},
        addTaskList: { list: [] },
        reduceTaskList: { list: [] },
        adjustTaskList: { list: [] },
        empInsPayList: { list: [] },
        empAccuPayList: { list: [] },
        empInsSerInfoList: { list: [] },
        empInsRefundInfoList: { list: [] },
        wageDataList: { list: [] },
        empLaborContInfoList: {},
        custBaseInfo: {},
        custConstList: { list: [] },
        crmquoDataList: { list: [] },
        onceChargeDataList: { list: [] },
        billList: { list: [] },
      },
    });
  };

  // 选择客户，雇员
  getChangeEmpName = value => {
    const { dispatch, form } = this.props;
    dispatch({
      type: 'integratedquery/updateModalData',
      payload: {
        type: value,
      },
    });
    form.resetFields();
  };

  // 客户搜索
  getCustList = value => {
    const { dispatch } = this.props;
    dispatch({
      type: 'integratedquery/getCustList',
      payload: {
        name: value,
      },
      callback: response => {
        if (response.success && response.data) {
          this.setState({ custList: response.data });
          if (response.data.length === 0) {
            message.warning('没有查询到该客户下的信息！');
          }
        } else {
          message.warning(response.message || '获取客户列表失败：服务器端错误');
        }
      },
    });
  };

  // 选择某一客户
  selectCust = (value, options) => {
    const {
      key,
      fsOptions: { custId, name },
    } = options;
    this.setState({ custId, name });
    const { dispatch } = this.props;
    dispatch({
      type: 'integratedquery/updateModalData',
      payload: {
        custLabelObj: { key, label: name },
        custShowName: value,
      },
    });
    // 客户基本信息
    dispatch({
      type: 'integratedquery/getCustBaseInfo',
      payload: {
        custId,
      },
    });
    // 商务合同
    dispatch({
      type: 'integratedquery/getCustContList',
      payload: {
        custId,
      },
    });
    // 报价单
    dispatch({
      type: 'integratedquery/getCrmquoList',
      payload: {
        custId,
      },
    });
    // 一次性收费
    dispatch({
      type: 'integratedquery/getOnceChargeList',
      payload: {
        custId,
        pageArg: { currentPage: 1, pageSize: 2 },
      },
    });
    // 客户账单
    dispatch({
      type: 'integratedquery/getBillList',
      payload: {
        custId,
        pageArg: { currentPage: 1, pageSize: 10 },
      },
    });
  };

  // 清空客户上一次搜索的历史记录
  emptyHistoryCust = () => {
    this.setState({ custList: [] });
  };

  // 雇员搜索
  getEmpList = value => {
    // 判断字符串中包含空格，特殊字符
    const reg = /^[\u4e00-\u9fa5_a-zA-Z0-9]+$/;
    let newValue = '';
    if (!reg.test(value)) {
      newValue = value.substring(value.indexOf('(') + 1, value.indexOf(')'));
    }
    const { dispatch } = this.props;
    dispatch({
      type: 'integratedquery/getEmpList',
      payload: {
        // eslint-disable-next-line no-unneeded-ternary
        empParam: newValue ? newValue : value,
      },
      callback: response => {
        if (response.success && response.data) {
          this.setState({ empList: response.data });
          if (response.data.length === 0) {
            message.warning('没有查询到该雇员下的信息！');
          }
        } else {
          message.warning(response.message || '获取雇员列表失败：服务器端错误');
        }
      },
    });
  };

  // 选择某一雇员
  selectEmp = (value, options) => {
    const {
      key,
      fsOptions: { cardNo, empId, empName },
    } = options;
    this.setState({ empName, certNo: cardNo });
    const { dispatch } = this.props;
    dispatch({
      type: 'integratedquery/updateModalData',
      payload: {
        empLabelObj: { key, label: `${empName} ${cardNo}` },
        empShowName: value,
      },
    });
    // 员工基本信息
    dispatch({
      type: 'integratedquery/getBaseInfo',
      payload: {
        empId, // 雇员id
      },
    });
    // 增员任务
    dispatch({
      type: 'integratedquery/getAddTaskList',
      payload: {
        empId,
      },
    });
    // 减员任务
    dispatch({
      type: 'integratedquery/getReduceTaskList',
      payload: {
        empId,
      },
    });
    // 调整任务
    dispatch({
      type: 'integratedquery/getAdjustTaskList',
      payload: {
        empId,
      },
    });
    // 社保实缴查询
    dispatch({
      type: 'integratedquery/getEmpInsPayInfo',
      payload: {
        certNo: cardNo, // 雇员身份证号
      },
    });
    // 公积金实缴查询
    dispatch({
      type: 'integratedquery/getEmpAccuPayInfo',
      payload: {
        certNo: cardNo,
      },
    });
    // 社保服务办理
    dispatch({
      type: 'integratedquery/getEmpInsSerInfo',
      payload: {
        certNo: cardNo, // 雇员身份证号
      },
    });
    // 返款信息
    dispatch({
      type: 'integratedquery/getEmpInsRefundInfo',
      payload: {
        certNo: cardNo, // 雇员身份证号
      },
    });
    // 代发工资
    dispatch({
      type: 'integratedquery/getWageInfoList',
      payload: {
        empId,
      },
    });
    // 劳动合同信息
    dispatch({
      type: 'integratedquery/getEmpLaborContInfo',
      payload: {
        empId,
      },
    });
  };

  // 清空雇员上一次搜索的历史记录
  emptyHistoryEmp = () => {
    this.setState({ empList: [] });
  };

  // 跳转
  jumpRouting = (targetRouter, id, taskSource, isSendId) => {
    let dynamicRouter;
    switch (targetRouter) {
      case 'contId':
        dynamicRouter = '/salemanage/busicont'; // 客户商务合同
        break;
      case 'quoId':
        dynamicRouter = '/salemanage/quotation'; // 客户报价单
        break;
      case 'onceFeeId':
        dynamicRouter = '/chargemanage/onebilling'; // 客户一次性收费
        break;
      case 'billId':
        dynamicRouter = '/chargemanage/customerbilling'; // 客户账单
        break;
      case 'addTaskId':
        dynamicRouter = '/customservicemanage/addemployee'; // 员工增员任务
        break;
      case 'deduTaskId':
        dynamicRouter = '/customservicemanage/reduceemployee'; // 员工减员任务
        break;
      case 'adjTaskId':
        dynamicRouter = '/customservicemanage/adjusttask'; // 员工调整任务
        break;
      case 'socialPay':
        dynamicRouter = '/socaccmanage/socsearrch'; // 员工社保实缴查询
        break;
      case 'accuPay':
        dynamicRouter = '/socaccmanage/accusearrch'; // 员工公积金实缴查询
        break;
      case 'insSerHdlId':
        dynamicRouter = '/socaccmanage/sochandle'; // 员工社保服务办理
        break;
      case 'refundInfoId':
        dynamicRouter = '/socaccmanage/rebate'; // 员工返款信息
        break;
      case 'wageOrderInfoId':
        dynamicRouter = '/salarymanage/protection'; // 员工代发工资
        break;
      case 'wageOrderProbId':
        dynamicRouter = '/salarymanage/protection'; // 员工代发工资问题人员
        break;
      case 'laborContId':
        dynamicRouter = '/customservicemanage/laborcontract'; // 员工劳动合同管理
        break;
      default:
    }
    const { custId, name, empName, certNo } = this.state;
    let pathname = null;
    if (id) {
      // 跳转详情页面
      if (targetRouter === 'wageOrderInfoId') {
        // 代发工资的详情
        pathname = `${dynamicRouter}/maintaindetail`;
      } else if (targetRouter === 'onceFeeId') {
        // 一次性收费详情
        pathname = `${dynamicRouter}/customerdetail`;
      } else if (targetRouter === 'adjTaskId') {
        // 调整任务的详情
        if (taskSource === 3) {
          // 人员及收费
          pathname = `${dynamicRouter}/persondetail`;
        } else {
          pathname = `${dynamicRouter}/detail`;
        }
      } else {
        pathname = `${dynamicRouter}/detail`;
      }
    } else {
      // 跳转首页
      pathname = `${dynamicRouter}/index`;
    }
    // 判断有没有任务来源，有没有调整类型
    if (targetRouter === 'addTaskId' || targetRouter === 'deduTaskId') {
      // 增员减员
      if (taskSource) {
        const routerParams = {
          pathname,
          query: {
            [targetRouter]: id,
            isMenuLink: false,
            taskSource,
            sendId: isSendId || null,
          },
          queryParam: { custId, name, empName, certNo },
        };
        router.push(routerParams);
      }
    } else if (targetRouter === 'adjTaskId') {
      // 调整任务
      if (taskSource) {
        const routerParams = {
          pathname,
          query: {
            [targetRouter]: id,
            isMenuLink: false,
            adjType: taskSource,
          },
          queryParam: { custId, name, empName, certNo },
        };
        router.push(routerParams);
      }
    } else if (targetRouter === 'refundInfoId') {
      // 返款信息
      if (taskSource) {
        const routerParams = {
          pathname,
          query: {
            [targetRouter]: id,
            isMenuLink: false,
            type: taskSource,
          },
          queryParam: { custId, name, empName, certNo },
        };
        router.push(routerParams);
      } else {
        const routerParams = {
          pathname,
          query: {
            [targetRouter]: id,
            isMenuLink: false,
          },
          queryParam: { empName },
        };
        router.push(routerParams);
      }
    } else {
      const routerParams = {
        pathname,
        query: {
          [targetRouter]: id,
          isMenuLink: false,
          activeKey: targetRouter === 'contId' ? 1 : null,
        },
        queryParam: { custId, name, empName, certNo },
      };
      router.push(routerParams);
    }
  };

  // 重置查询条件并获取列表
  async resetAndGeLlist(location) {
    const { dispatch, form } = this.props;
    dispatch({
      type: 'global/changeIsMenuLink',
      payload: location,
    });
    await this.delAllListData();
    form.resetFields();
  }

  render() {
    const { empList, custList } = this.state;
    const { form, type, custShowName, empShowName } = this.props;
    const { getFieldDecorator } = form;
    // 雇员列表查询
    let options = null;
    if (empList && empList.length) {
      options = empList.map(opt => (
        <Option
          key={`${opt.empId} ${opt.cardNo}`}
          value={`${opt.empName} (${opt.cardNo})`}
          fsOptions={opt}
        >
          {`${opt.empName} (${opt.cardNo})`}
        </Option>
      ));
    }
    // 客户列表查询
    let custoptions = null;
    if (custList && custList.length) {
      custoptions = custList.map(opt => (
        <Option key={opt.custId} value={opt.name} fsOptions={opt}>
          {opt.name}
        </Option>
      ));
    }
    return (
      <PageHeaderWrapper>
        <Card className={styles.searchCard} style={{ marginBottom: 0 }}>
          <div className={styles.searchManageBox}>
            <Row>
              <Col span={12} offset={6}>
                <Select
                  value={type}
                  style={{
                    display: 'inline-block',
                    marginRight: -2,
                    fontSize: 14,
                    float: 'left',
                    width: '80px',
                    marginTop: 1,
                  }}
                  size="large"
                  onSelect={value => this.getChangeEmpName(value)}
                >
                  <Option value={1}>客户</Option>
                  <Option value={2}>雇员</Option>
                </Select>
                {type === 1 ? (
                  <FormItem style={{ float: 'left', width: '75%' }}>
                    {getFieldDecorator('custForm', {
                      initialValue: custShowName,
                    })(
                      <AutoComplete
                        size="large"
                        style={{ width: '100%' }}
                        // labelInValue
                        dataSource={custoptions}
                        onSelect={this.selectCust}
                        onChange={this.emptyHistoryCust}
                      >
                        <Search
                          placeholder="请输入"
                          enterButton="搜索"
                          size="large"
                          style={{ width: '100%' }}
                          onSearch={value => this.getCustList(value)}
                        />
                      </AutoComplete>
                    )}
                  </FormItem>
                ) : (
                  <FormItem style={{ float: 'left', width: '75%' }}>
                    {getFieldDecorator('empForm', {
                      initialValue: empShowName,
                    })(
                      <AutoComplete
                        size="large"
                        // labelInValue
                        style={{ width: '100%' }}
                        dataSource={options}
                        onSelect={this.selectEmp}
                        onChange={this.emptyHistoryEmp}
                      >
                        <Search
                          placeholder="请输入"
                          enterButton="搜索"
                          size="large"
                          style={{ width: '100%' }}
                          onSearch={value => this.getEmpList(value)}
                        />
                      </AutoComplete>
                    )}
                  </FormItem>
                )}
              </Col>
            </Row>
          </div>
        </Card>
        {type === 1 ? (
          <div className={styles.antAnchorDefaultBg}>
            <Anchor
              onClick={e => e.preventDefault()}
              style={{ background: '#f0f2f5' }}
              targetOffset={50}
            >
              <Row type="flex" justify="space-around">
                <Col>
                  <Link href="#customerbasicinfor" title="客户基本信息" />
                </Col>
                <Authorized authority="cs:custCont:getList" noMatch={null}>
                  <Col>
                    <Link href="#businesscontract" title="商务合同" />
                  </Col>
                </Authorized>
                <Authorized authority="cs:crmquo:getList" noMatch={null}>
                  <Col>
                    <Link href="#quotation" title="报价单" />
                  </Col>
                </Authorized>
                <Authorized authority="cs:onceCust:listCust" noMatch={null}>
                  <Col>
                    <Link href="#oncecharge" title="一次性收费" />
                  </Col>
                </Authorized>
                <Authorized authority="cs:csBill:getList" noMatch={null}>
                  <Col>
                    <Link href="#customerbill" title="客户账单" />
                  </Col>
                </Authorized>
              </Row>
            </Anchor>
          </div>
        ) : (
          <div className={styles.antAnchorDefaultBg}>
            <Anchor
              onClick={e => e.preventDefault()}
              style={{ background: '#f0f2f5' }}
              targetOffset={50}
            >
              <Row type="flex" justify="space-around">
                <Col>
                  <Link href="#basicinfor" title="员工基本信息" />
                </Col>
                <Authorized authority="cs:csoder:addemp" noMatch={null}>
                  <Col>
                    <Link href="#increasetask" title="增员任务" />
                  </Col>
                </Authorized>
                <Authorized authority="cs:csoder:reemp" noMatch={null}>
                  <Col>
                    <Link href="#attritiontask" title="减员任务" />
                  </Col>
                </Authorized>
                <Authorized authority="cs:csoder:change" noMatch={null}>
                  <Col>
                    <Link href="#adjusttask" title="调整任务" />
                  </Col>
                </Authorized>
                <Authorized authority="business:social:socialpay" noMatch={null}>
                  <Col>
                    <Link href="#socialsecuritypayment" title="社保实缴查询" />
                  </Col>
                </Authorized>
                <Authorized authority="business:provident:query" noMatch={null}>
                  <Col>
                    <Link href="#providentfundpayment" title="公积金实缴查询" />
                  </Col>
                </Authorized>
                <Authorized authority="business:social:handle" noMatch={null}>
                  <Col>
                    <Link href="#socialsecurityservice" title="社保服务办理" />
                  </Col>
                </Authorized>
                <Authorized authority="business:fm:rebate" noMatch={null}>
                  <Col>
                    <Link href="#rebateinformation" title="返款信息" />
                  </Col>
                </Authorized>
                <Authorized authority="business:wage:maintain" noMatch={null}>
                  <Col>
                    <Link href="#payroll" title="代发工资" />
                  </Col>
                </Authorized>
                <Authorized authority="cs:csoder:laborcont" noMatch={null}>
                  <Col>
                    <Link href="#laborcontractinfor" title="劳动合同信息" />
                  </Col>
                </Authorized>
              </Row>
            </Anchor>
          </div>
        )}
        {type === 1 ? (
          <div>
            <CustomerBasicInfor />
            <Authorized authority="cs:custCont:getList" noMatch={null}>
              <BusinessContract jumpRouting={this.jumpRouting} />
            </Authorized>
            <Authorized authority="cs:crmquo:getList" noMatch={null}>
              <Quotation jumpRouting={this.jumpRouting} />
            </Authorized>
            <Authorized authority="cs:onceCust:listCust" noMatch={null}>
              <OnceCharge jumpRouting={this.jumpRouting} />
            </Authorized>
            <Authorized authority="cs:csBill:getList" noMatch={null}>
              <CustomerBill jumpRouting={this.jumpRouting} />
            </Authorized>
          </div>
        ) : (
          <div>
            <BasicInfor />
            <Authorized authority="cs:csoder:addemp" noMatch={null}>
              <AddEmploeTask jumpRouting={this.jumpRouting} />
            </Authorized>
            <Authorized authority="cs:csoder:reemp" noMatch={null}>
              <ReduceEmploeTask jumpRouting={this.jumpRouting} />
            </Authorized>
            <Authorized authority="cs:csoder:change" noMatch={null}>
              <AdjustTask jumpRouting={this.jumpRouting} />
            </Authorized>
            <Authorized authority="business:social:socialpay" noMatch={null}>
              <PaymentInfor jumpRouting={this.jumpRouting} />
            </Authorized>
            <Authorized authority="business:social:handle" noMatch={null}>
              <SocialHandleInfor jumpRouting={this.jumpRouting} />
            </Authorized>
            <Authorized authority="business:fm:rebate" noMatch={null}>
              <RefundInfor jumpRouting={this.jumpRouting} />
            </Authorized>
            <Authorized authority="business:wage:maintain" noMatch={null}>
              <Payroll jumpRouting={this.jumpRouting} />
            </Authorized>
            <Authorized authority="cs:csoder:laborcont" noMatch={null}>
              <LaborContractInfor jumpRouting={this.jumpRouting} />
            </Authorized>
          </div>
        )}
      </PageHeaderWrapper>
    );
  }
}

export default SearchList;
